package com.example.demo.algorithm.lesson.basic.class3;

import com.example.demo.algorithm.lesson.basic.class1.ArrayCompareHelper;

import java.util.Arrays;

/**
 * @author liweizhi
 * @date 2020/5/6
 */
public class SmallSum {
    public static long smallSum(int[] arr) {
        if (arr == null || arr.length < 2) {
            return 0;
        }
        return process(arr, 0, arr.length - 1);
    }

    public static long process(int[] arr, int left, int right) {
        if (left == right) {
            return 0L;
        }
        int mid = left + ((right - left) >> 1);
        return process(arr, left, mid) +
                process(arr, mid + 1, right) +
                merge(arr, left, mid, right);
    }

    public static long merge(int[] arr, int left, int mid, int right) {
        int[] helper = new int[right - left + 1];
        int i = 0;
        int p1 = left;
        int p2 = mid + 1;
        long ret = 0L;
        while (p1 <= mid && p2 <= right) {
            if (arr[p1] >= arr[p2]) {
                helper[i] = arr[p2];
                p2++;
            } else {
                ret += arr[p1] * (right - p2 + 1);
                helper[i] = arr[p1];
                p1++;
            }
            i++;
        }
        while (p1 <= mid) {
            helper[i++] = arr[p1++];
        }
        while (p2 <= right) {
            helper[i++] = arr[p2++];
        }
        for (int j = 0; j < helper.length; j++) {
            arr[left + j] = helper[j];
        }
        return ret;
    }

    public static long comparator(int[] arr) {
        if (arr == null || arr.length < 2) {
            return 0L;
        }
        long ret = 0L;
        for (int i = 1; i < arr.length; i++) {
            for (int j = 0; j < i; j++) {
                if (arr[j] < arr[i]) {
                    ret += arr[j];
                }
            }
        }
        return ret;
    }

    public static void main(String[] args) {
        int[] arr = {3, 2, 1, 5};
        int[] arr2 = ArrayCompareHelper.copyArray(arr);
        System.out.println(smallSum(arr));
        System.out.println(comparator(arr2));
    }
}
